package com.johnny.dataStructures.stack;


class LinkedListStack {
    private Node first = new Node(0);

    /**
     * 添加栈
     *
     * @param no
     */
    public void push(int no) {
        Node node = new Node(no);
        Node temp = first;
        boolean flag = false;
        while (true) {
            if (temp.next == null) {  //到达尾几点，可以添加
                flag = true;
                break;
            }
            temp = temp.next;

        }
        if (flag) {
            temp.next = node;  //添加
        }
    }

    /**
     * 显示栈
     */
    public void list() {
        Node temp = first.next;
        while (true) {
            if (isEmpty()) {
                System.out.println("栈为空");
                break;
            }
            if (temp != null) {
                System.out.println(temp.toString());
                temp = temp.next;
            } else {
                break;
            }
        }
    }

    /**
     * 移除栈
     */
    public void pop() {
        Node node = first;
        if (node.next == null) {
            System.out.println("该栈为空");
            return;
        }
        while (true) {
            Node temp = node;
            node = node.next;
            if (node.next == null) {
                System.out.printf("移除该节点no=%d\n", node.no);
                temp.next = null;
                break;
            }
        }
    }

    public boolean isEmpty() {
        Node temp = first;
        if (temp.next == null) {
            return true;
        }
        return false;
    }

}

class Node {
    public int no;
    public Node next;

    public Node(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                '}';
    }
}

public class LinkedListStackDemo {

    public static void main(String[] args) {
        LinkedListStack stack = new LinkedListStack();
        stack.push(11);
        stack.push(21);
        stack.push(31);
        stack.push(41);
        stack.push(51);
        stack.push(61);
        stack.push(71);
        stack.push(81);
        stack.list();
        System.out.println("删除节点显示");
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.list();
    }
}
